package com.tianxia120.website.data.utils;

import cn.hutool.core.util.StrUtil;
import com.jfinal.plugin.activerecord.Record;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @createTime: 2017/12/29
 * @author: HingLo
 * @description: 字符串处理工具类
 */
public class CommonUtils {

    /**
     * 定义数组不是null，不是空白字符串
     *
     * @param str 待校验的字符串数组
     * @return boolean
     */
    public static boolean isNotBlank(String... str) {
        for (String s : str) {
            if (StrUtil.isBlank(s)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 通过图片的名称与类型组装访问图片的链接
     *
     * @param name 图片名称
     * @param type 图片类型
     * @return 完整的请求链接
     */
    public static String imgInstall(String name, int type) {
        return FieldUtils.URL + StrUtil.removePrefix(FileImageUtils.readUrlUtils(type), FileImageUtils.ROOT) + name;
    }

    /**
     * 获取用户的Ip地址
     *
     * @return
     */
    public static String getRemortIP(HttpServletRequest request) {
        String ip = request.getHeader("X-requested-For");
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null && ip.contains(",")) {
            String[] ips = ip.split(",");
            for (String strIp : ips) {
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }

        return ip;
    }

    /**
     * 判断指定的方法上是否拥有指定的注解<br>
     * 一般用于拦截前中做权限拦截
     *
     * @param method         Method 对象
     * @param annotationType 指定的注解class类型
     * @param <T>            泛型
     * @return 是否有指定的注解
     */
    public static <T extends Annotation> boolean hasMethodAnnotation(Method method, Class<T> annotationType) {
        //返回方法是否拥有指定类型的注解
        T t = method.getAnnotation(annotationType);
        return t != null;
    }

    public static void main(String[] args) {
        Record record=new Record().set("h",12);
        System.out.println(record.getLong("h"));
    }

}

